package com.migration.controller;

import com.migration.model.migration.MigrationScript;
import com.migration.service.MigrationScriptService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 数据迁移脚本控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/migration/scripts")
@Tag(name = "数据迁移脚本接口", description = "提供基于脚本的数据库迁移功能")
public class MigrationScriptController {

    private final MigrationScriptService migrationScriptService;
    private final ExecutorService executorService = Executors.newSingleThreadExecutor();

    /**
     * 构造函数，注入迁移脚本服务
     */
    @Autowired
    public MigrationScriptController(MigrationScriptService migrationScriptService) {
        this.migrationScriptService = migrationScriptService;
    }

    /**
     * 获取所有迁移脚本
     *
     * @return 迁移脚本列表
     */
    @GetMapping
    @Operation(
        summary = "获取所有迁移脚本",
        description = "获取系统中所有已注册的迁移脚本信息",
        responses = {
            @ApiResponse(
                responseCode = "200",
                description = "获取成功",
                content = @Content(mediaType = "application/json")
            )
        }
    )
    public ResponseEntity<List<MigrationScript>> getAllScripts() {
        log.info("获取所有迁移脚本");
        return ResponseEntity.ok(migrationScriptService.getAllScripts());
    }

    /**
     * 获取指定名称的迁移脚本
     *
     * @param name 脚本名称
     * @return 迁移脚本
     */
    @GetMapping("/{name}")
    @Operation(
        summary = "获取指定迁移脚本",
        description = "根据名称获取指定的迁移脚本信息",
        responses = {
            @ApiResponse(
                responseCode = "200",
                description = "获取成功",
                content = @Content(mediaType = "application/json")
            ),
            @ApiResponse(
                responseCode = "404",
                description = "脚本不存在",
                content = @Content(mediaType = "application/json")
            )
        }
    )
    public ResponseEntity<MigrationScript> getScriptByName(
            @Parameter(description = "脚本名称")
            @PathVariable String name) {
        log.info("获取迁移脚本: {}", name);
        MigrationScript script = migrationScriptService.getScriptByName(name);
        if (script == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(script);
    }

    /**
     * 执行指定名称的迁移脚本
     *
     * @param name 脚本名称
     * @return 执行结果
     */
    @PostMapping("/{name}/execute")
    @Operation(
        summary = "执行指定迁移脚本",
        description = "执行指定名称的数据迁移脚本",
        responses = {
            @ApiResponse(
                responseCode = "200",
                description = "执行成功",
                content = @Content(mediaType = "application/json")
            ),
            @ApiResponse(
                responseCode = "400",
                description = "执行失败",
                content = @Content(mediaType = "application/json")
            )
        }
    )
    public ResponseEntity<Map<String, Object>> executeScript(
            @Parameter(description = "脚本名称")
            @PathVariable String name) {
        log.info("执行迁移脚本: {}", name);
        try {
            Map<String, Object> result = migrationScriptService.executeMigrationScript(name);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("执行迁移脚本失败", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 执行所有迁移脚本
     *
     * @return 执行结果
     */
    @PostMapping("/execute-all")
    @Operation(
        summary = "执行所有迁移脚本",
        description = "按序执行所有已注册的数据迁移脚本",
        responses = {
            @ApiResponse(
                responseCode = "200",
                description = "执行成功",
                content = @Content(mediaType = "application/json")
            ),
            @ApiResponse(
                responseCode = "400",
                description = "执行失败",
                content = @Content(mediaType = "application/json")
            )
        }
    )
    public ResponseEntity<Map<String, Object>> executeAllScripts() {
        log.info("执行所有迁移脚本");
        try {
            Map<String, Object> result = migrationScriptService.executeAllMigrationScripts();
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("执行所有迁移脚本失败", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

}
